package ren.steve.ngh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ren.steve.model.ngh.bean.NghQueryResult;
import ren.steve.model.ngh.bean.NghQueryTab;
import ren.steve.ngh.mapper.NghQueryResultMapper;
import ren.steve.ngh.mapper.NghQueryTabMapper;
import ren.steve.ngh.service.NghQueryTabService;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @Author: CIS-T-13 Liu GuoJia
 * @Description:
 * @Date: Created in 2024/3/25 16:18
 */

@Service
public class NghQueryTabServiceImpl extends ServiceImpl<NghQueryTabMapper, NghQueryTab> implements NghQueryTabService {

  @Autowired
  NghQueryTabMapper nghQueryTabMapper;

  @Autowired
  NghQueryResultMapper nghQueryResultMapper;

  @Override
  public List<NghQueryTab> list(String user) {
    QueryWrapper<NghQueryTab> wrapper = new QueryWrapper<>();
    wrapper.eq("user", user.toUpperCase());
    return nghQueryTabMapper.selectList(wrapper);
  }

  @Override
  public NghQueryTab insert(NghQueryTab tab, List<NghQueryTab> tabs) {
    NghQueryTab newTab = new NghQueryTab();
    newTab.setUser(tab.getUser());
    List<Integer> nums = IntStream.rangeClosed(1, 20).boxed().collect(Collectors.toList());
    for (NghQueryTab item : tabs) {
      String[] split = item.getLabel().split("_");
      Integer num = Integer.valueOf(split[1]);
      int index = nums.indexOf(num);
      if (index >= 0) {
        nums.remove(index);
      }
    }
    newTab.setLabel("TAB_" + nums.get(0).toString());
    int result = nghQueryTabMapper.insert(newTab);
    if (result == 1) {
      return newTab;
    } else {
      return null;
    }
  }

  @Override
  public int delete(Integer id) {
    QueryWrapper<NghQueryResult> wrapper = new QueryWrapper<>();
    wrapper.eq("tab_id", id);
    nghQueryResultMapper.delete(wrapper);
    return nghQueryTabMapper.deleteById(id);
  }

  @Override
  public int deleteBatch(String[] ids) {
    ArrayList<Integer> list = new ArrayList<>();
    for (String id : ids) {
      list.add(Integer.valueOf(id));
    }
    return nghQueryTabMapper.deleteBatchIds(list);
  }

  @Override
  public NghQueryTab update(NghQueryTab tab) {
    int result = nghQueryTabMapper.updateById(tab);
    if (result == 1) {
      return nghQueryTabMapper.selectById(tab.getId());
    }
    return null;
  }

  @Override
  public NghQueryTab selectById(Integer id) {
    NghQueryTab tab = nghQueryTabMapper.selectById(id);
    QueryWrapper<NghQueryResult> wrapper = new QueryWrapper<>();
    wrapper.eq("tab_id", tab.getId());
    List<NghQueryResult> results = nghQueryResultMapper.selectList(wrapper);
    tab.setResults(results);
    return tab;
  }


}
